

public class DES {
    // Replacement Table（RT）IP置换表
    final static int[] RT_IP = { 58, 50, 42, 34, 26, 18, 10, 2,
            60, 52, 44, 36, 28, 20, 12, 4,
            62, 54, 46, 38, 30, 22, 14, 6,
            64, 56, 48, 40, 32, 24, 16, 8,
            57, 49, 41, 33, 25, 17, 9,  1,
            59, 51, 43, 35, 27, 19, 11, 3,
            61, 53, 45, 37, 29, 21, 13, 5,
            63, 55, 47, 39, 31, 23, 15, 7 };

    // 密钥选择（置换）表，64位密钥去掉校验位，选择剩下的56位作为新的密钥。可以发现，去掉校验位的同时还打乱了顺序
    final static int[] RT_Key = {57, 49, 41, 33, 25, 17, 9,
            1, 58, 50, 42, 34, 26, 18,
            10,  2, 59, 51, 43, 35, 27,
            19, 11,  3, 60, 52, 44, 36,
            63, 55, 47, 39, 31, 23, 15,
            7, 62, 54, 46, 38, 30, 22,
            14,  6, 61, 53, 45, 37, 29,
            21, 13,  5, 28, 20, 12,  4};

    // 压缩置换，将56位密钥压缩成48位子密钥
    final static int[] RT_Compress = {14, 17, 11, 24,  1,  5,
            3, 28, 15,  6, 21, 10,
            23, 19, 12,  4, 26,  8,
            16,  7, 27, 20, 13,  2,
            41, 52, 31, 37, 47, 55,
            30, 40, 51, 45, 33, 48,
            44, 49, 39, 56, 34, 53,
            46, 42, 50, 36, 29, 32};

    // 每轮左移的位数
    final static int[] shiftBits = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};

    // 扩展置换表 RT_E，将32位扩展至48位
    final static int[] RT_E = {32,  1,  2,  3,  4,  5,
            4,  5,  6,  7,  8,  9,
            8,  9, 10, 11, 12, 13,
            12, 13, 14, 15, 16, 17,
            16, 17, 18, 19, 20, 21,
            20, 21, 22, 23, 24, 25,
            24, 25, 26, 27, 28, 29,
            28, 29, 30, 31, 32,  1};

    // S盒，每个S盒Si是4x16的置换表，6位 -> 4位
    final static int[][][] S_BOX ={
            {
                    {14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7},
                    {0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8},
                    {4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0},
                    {15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13}
            },
            {
                    {15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10},
                    {3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5},
                    {0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15},
                    {13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9}
            },
            {
                    {10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8},
                    {13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1},
                    {13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7},
                    {1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12}
            },
            {
                    {7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15},
                    {13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9},
                    {10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4},
                    {3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14}
            },
            {
                    {2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9},
                    {14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6},
                    {4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14},
                    {11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3}
            },
            {
                    {12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11},
                    {10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8},
                    {9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6},
                    {4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13}
            },
            {
                    {4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1},
                    {13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6},
                    {1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2},
                    {6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12}
            },
            {
                    {13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7},
                    {1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2},
                    {7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8},
                    {2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11}
            }
    };

    // P置换，32位 -> 32位
    final static int[] RT_P = {16,  7, 20, 21,
            29, 12, 28, 17,
            1, 15, 23, 26,
            5, 18, 31, 10,
            2,  8, 24, 14,
            32, 27,  3,  9,
            19, 13, 30,  6,
            22, 11,  4, 25 };

    // 逆IP置换表
    final static int[] RT_InverseIP = {40, 8, 48, 16, 56, 24, 64, 32,
            39, 7, 47, 15, 55, 23, 63, 31,
            38, 6, 46, 14, 54, 22, 62, 30,
            37, 5, 45, 13, 53, 21, 61, 29,
            36, 4, 44, 12, 52, 20, 60, 28,
            35, 3, 43, 11, 51, 19, 59, 27,
            34, 2, 42, 10, 50, 18, 58, 26,
            33, 1, 41,  9, 49, 17, 57, 25};

    /**********************************************************************/
    /*                                                                    */
    /*                            下面是DES算法实现                         */
    /*                                                                    */
    /**********************************************************************/

    //生成16个子密钥
    public static StringBuffer[] GenerateSubKey(StringBuffer str, boolean flag) throws Exception{
        if(str.length()!=64){
            throw new Exception("输入密钥长度不是64位！");
        }
        else {
            //密钥选择
            StringBuffer choosedKey = new StringBuffer();
            for (int i = 0; i < RT_Key.length; i++) {
                choosedKey.append(str.charAt(RT_Key[i]-1));
            }
            //拆分密钥
//            System.out.println("choosedKey.length():"+choosedKey.length());
            StringBuffer leftString = new StringBuffer(choosedKey.substring(0,28));
            StringBuffer rightString = new StringBuffer(choosedKey.substring(28,56));

            //16次循环得到16个子密钥
            StringBuffer[] res = new StringBuffer[16];
            for (int i = 0; i < 16; i++) {
                int shiftBit=shiftBits[i];
                //两部分密钥分别左移
                StringBuffer temp_left=new StringBuffer(leftString);
                StringBuffer temp_right=new StringBuffer(rightString);
                for (int j = 0; j < leftString.length(); j++) {
                    if(j-shiftBit<0){
                        leftString.setCharAt(j,temp_left.charAt(j-shiftBit+28));
                        rightString.setCharAt(j,temp_right.charAt(j-shiftBit+28));
                    }else{
                        leftString.setCharAt(j,temp_left.charAt(j-shiftBit));
                        rightString.setCharAt(j,temp_right.charAt(j-shiftBit));
                    }
                }
                //压缩置换
                StringBuffer temp=new StringBuffer(leftString);
                StringBuffer input = temp.append(rightString);
                StringBuffer subKey = new StringBuffer();
                for (int k = 0; k < RT_Compress.length; k++) {
                    subKey.append(input.charAt(RT_Compress[k]-1));
                }
                res[i]=subKey;
            }
            StringBuffer[] res_reverse = new StringBuffer[16];
            for (int i = 0; i < res.length; i++) {
                res_reverse[i]=res[res.length-i-1];
            }
            return flag?res:res_reverse;
        }
    }

    //IP置换
    public static StringBuffer IPReplacement(StringBuffer str){
        StringBuffer res = new StringBuffer();
        for (int i = 0; i < RT_IP.length; i++) {
            res.append(str.charAt(RT_IP[i]-1));
        }
        return res;
    }

    //执行F密码函数
    public static StringBuffer function(StringBuffer subKey, StringBuffer R) throws Exception {
        //1.扩展置换
        StringBuffer extendedString = new StringBuffer();
        for (int i = 0; i < RT_E.length; i++) {
            extendedString.append(R.charAt(RT_E[i]-1));
        }
        //2.异或操作
        StringBuffer xor = XOR(extendedString, subKey);
        if(xor.length()!=48){
            throw new Exception("异或结果不等于48位！");
        }else{
            //3.S盒
            StringBuffer S_output =new StringBuffer();
            for (int i = 0; i < 8; i++) {
                //3.1 拆分为6位子串substring
                String substring = xor.substring(6 * i, 6 * (i+1));
                //3.2 将substring取0,5位为x;其余4位为y【二进制转换】
                int x=binaryToDecimal(substring.substring(0,1)+substring.substring(5,6));
                int y=binaryToDecimal(substring.substring(1,5));
                //3.3 从S盒取S[i][x][y]转化为4位输出
                String s = Integer.toBinaryString(S_BOX[i][x][y]);
                StringBuffer stringBuffer = new StringBuffer(s);
                //3.4 如果输出未达到4位则往前补0，补齐4位
                while(4-stringBuffer.length()!=0){
                    stringBuffer.insert(0,'0');
                }
                S_output.append(stringBuffer);
            }
            //4.P盒
            StringBuffer res = new StringBuffer();
            for (int i = 0; i < RT_P.length; i++) {
                res.append(S_output.charAt(RT_P[i]-1));
            }
            return res;
        }
    }

    //执行异或操作
    public static StringBuffer XOR(StringBuffer L, StringBuffer output) throws Exception{

        if(L.length()!=output.length()){
            throw new Exception("两者长度不同，不能进行异或运算！");
        }else{
            StringBuffer res = new StringBuffer(L.length());
            for (int i = 0; i < L.length(); i++) {
                int temp =0;
                if(L.charAt(i)!=output.charAt(i)){temp=1;}
                res.append(temp);
            }
            return res;
        }
    }

    //逆IP置换
    public static StringBuffer ReverseIPReplacement(StringBuffer str){
        StringBuffer res = new StringBuffer();
        for (int i = 0; i < RT_InverseIP.length; i++) {
            res.append(str.charAt(RT_InverseIP[i]-1));
        }
        return res;
    }

    //二进制转化为10进制
    public static int binaryToDecimal(String str){
        int len  = str.length();
        int res=0;
        for (int i = 0; i < len; i++) {
            res+=Integer.parseInt(String.valueOf(str.charAt(len-i-1)))*Math.pow(2,i);
        }
        return res;
    }

    //完整加密过程
    public static StringBuffer Encryption(StringBuffer Plaintext, StringBuffer Key) throws Exception {
        //1.获取子密钥
        StringBuffer[] subKeys =GenerateSubKey(Key,true);
        //2.IP置换
        StringBuffer stringBuffer = IPReplacement(Plaintext);
        StringBuffer Leftstring = new StringBuffer(stringBuffer.substring(0, 32));
        StringBuffer Rightstring = new StringBuffer(stringBuffer.substring(32,64));
        //3.for循环16轮
        for (int i = 0; i < 16; i++) {
            //3.1 f函数
            StringBuffer f_output=function(subKeys[i],Rightstring);
            //3.2 异或
            StringBuffer temp=XOR(Leftstring,f_output);
            //3.3 更新Li和Ri
            Leftstring=Rightstring;
            Rightstring=temp;
        }
        //4.左右互换
        StringBuffer res = Rightstring.append(Leftstring);
        //5.逆IP置换
        res=ReverseIPReplacement(res);
        return  res;
    }

    //完整解密过程
    public static StringBuffer Decryption(StringBuffer Plaintext, StringBuffer Key) throws Exception {
        //1.获取子密钥
        StringBuffer[] subKeys =GenerateSubKey(Key,false);
        //2.IP置换
        StringBuffer stringBuffer = IPReplacement(Plaintext);
        StringBuffer Leftstring = new StringBuffer(stringBuffer.substring(0, 32));
        StringBuffer Rightstring = new StringBuffer(stringBuffer.substring(32,64));
        //3.for循环16轮
        for (int i = 0; i < 16; i++) {
            //3.1 f函数
            StringBuffer f_output=function(subKeys[i],Rightstring);
            //3.2 异或
            StringBuffer temp=XOR(Leftstring,f_output);
            //3.3 更新Li和Ri
            Leftstring=Rightstring;
            Rightstring=temp;
        }
        //4.左右互换
        StringBuffer res = Rightstring.append(Leftstring);
        //5.逆IP置换
        res=ReverseIPReplacement(res);
        return  res;
    }


    /**********************************************************************/
    /*                                                                    */
    /*                            下面是测试代码                             */
    /*                                                                    */
    /**********************************************************************/

//    a) 使用同一密钥，对两组明文进行加密和解密。
//            64位密钥：
//            00000010 10010110 01001000 11000100 00111000 00110000 00111000 01100100
//
//            64位明文块1：
//            00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
//
//            64位明文块2（与明文块1仅有一位的不同）：
//            10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
//
//    输出两个密文块的二进制流，统计两个密文块间不同数据位的数量。
//
//    b) 对同一段明文，使用不同密钥进行加密和解密操作。
//            64位密钥1：
//            11100010 11110110 11011110 00110000 00111010 00001000 01100010 11011100
//
//            64位密钥2（与密钥1仅有一位的不同）：
//            01100010 11110110 11011110 00110000 00111010 00001000 01100010 11011100
//
//    明文：
//            01101000 10000101 00101111 01111010 00010011 01110110 11101011 10100100
//
//    输出两个密文块的二进制流，统计两个密文块间不同数据位的数量。


    public static void main(String[] args) throws Exception {

        System.out.println();
        System.out.println("a):使用同一密钥，对两组明文进行加密");
        String key ="00000010 10010110 01001000 11000100 00111000 00110000 00111000 01100100";
        String plaintext_1 ="00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000";
        String plaintext_2 ="10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000";
        StringBuffer Key= new StringBuffer(key.replaceAll(" ",""));
        StringBuffer Plaintext_1= new StringBuffer(plaintext_1.replaceAll(" ",""));
        StringBuffer Plaintext_2= new StringBuffer(plaintext_2.replaceAll(" ",""));
        StringBuffer Ciphertext_1 = Encryption(Plaintext_1, Key);
        StringBuffer Ciphertext_2 = Encryption(Plaintext_2, Key);
        System.out.println("密钥："+Key);
        System.out.println("明文1："+Plaintext_1);
        System.out.println("明文2："+Plaintext_2);
        System.out.println("========================================================================");
        System.out.println("密文1："+Ciphertext_1);
        System.out.println("密文2："+Ciphertext_2);
        Helper(Ciphertext_1, Ciphertext_2);
        System.out.println();


        System.out.println("b):对同一段明文，使用不同密钥进行加密操作");
        String key_1 ="11100010 11110110 11011110 00110000 00111010 00001000 01100010 11011100";
        String key_2 ="01100010 11110110 11011110 00110000 00111010 00001000 01100010 11011100";
        String plaintext ="01101000 10000101 00101111 01111010 00010011 01110110 11101011 10100100";
        StringBuffer Key_1= new StringBuffer(key_1.replaceAll(" ",""));
        StringBuffer Key_2= new StringBuffer(key_2.replaceAll(" ",""));
        StringBuffer Plaintext= new StringBuffer(plaintext.replaceAll(" ",""));
        StringBuffer Ciphertext_b1 = Encryption(Plaintext_1, Key);
        StringBuffer Ciphertext_b2 = Encryption(Plaintext_2, Key);
        System.out.println("密钥1："+Key_1);
        System.out.println("密钥2："+Key_2);
        System.out.println("明文："+Plaintext);
        System.out.println("===========================================================================");
        System.out.println("密文1："+Ciphertext_b1);
        System.out.println("密文2："+Ciphertext_b2);
        Helper(Ciphertext_b1, Ciphertext_b2);
        System.out.println();


        System.out.println("c):附加，对一个明文和密钥，先加密后解密");
        StringBuffer Ciphertext_c = Encryption(Plaintext_1, Key);
        StringBuffer Plaintext_c = Decryption(Ciphertext_c, Key);
        System.out.println("明文："+Plaintext_1);
        System.out.println("密钥："+Key);
        System.out.println("===========================================================================");
        System.out.println("加密后密文："+Ciphertext_c);
        System.out.println("再解密后明文："+Plaintext_c);
    }

    //帮助统计两个比特流之间不同的位数的数量
    public static void Helper(StringBuffer str1,StringBuffer str2){
        int res=0;
        for (int i = 0; i < str1.length(); i++) {
            int add=str1.charAt(i)==str2.charAt(i)?0:1;
            res+=add;
        }
        System.out.println("两个密文块间不同数据位的数量为:"+res);
    }
}

